<template>
	<view class="my-avatar-view">
		<view class="my-avatar" v-if="preview" @click.stop="onAvatarClick">
			<image
				v-if="isShow"
				class="my-avatar__image"
				:class="[`my-avatar__image--${shape}`]"
				:src="srcurl || defaultUrl"
				:mode="mode"
				@error="errorHandler"
				:style="[{
					width: size,
					height: size
				}]"
			></image>
		</view>
		<view class="my-avatar" @click="onAvatarClick" v-else>
			<image
				v-if="isShow"
				class="my-avatar__image"
				:class="[`my-avatar__image--${shape}`]"
				:src="srcurl || defaultUrl"
				:mode="mode"
				@error="errorHandler"
				:style="[{
					width: size,
					height: size
				}]"
			></image>
		</view>
	</view>
</template>

<script>
	import mediaCache from '@/common/mediacache/mediaCache.js'; // 适配你的实际路径
	export default {
		props: {
			src: {
				type: String,
				default: ''
			},
			shape: {
				type: String,
				default: 'circle'
			},
			size: {
				type: [String, Number],
				default: 40
			},
			mode: {
				type: String,
				default: 'scaleToFill'
			},
			defaultUrl: {
				type: String,
				default:"/static/logo.png"
			},
			preview:{
				type:Boolean,
				default:false
			}
		},
		data() {
			return {
				srcurl: '',
				fileTpye:'image',
				uploadType: 'avatar',
				isload:false,
				isShow:false,
				isRenewal:false
			};
		},
		watch: {
			src(newVal, oldVal) {
				if(!newVal) {
					this.errorHandler()
					return
				}
				this.isRenewal = true
				if(this.isShow){
					this.loadImage();
				}
				
			}
		},
		mounted() {
			this.createIntersectionObserver();
			// this.loadImage();
		},
		methods: {
			createIntersectionObserver() {
			  this.$nextTick(() => {
			    this.$nextTick(() => {
			      this.observer = uni.createIntersectionObserver(this);
			      this.observer.relativeToViewport().observe('.my-avatar', (res) => {
			        if (res.intersectionRatio > 0) {
			          if (!this.isload || this.isRenewal) this.loadImage();
			          this.isShow = true
			        } else {
			          this.isShow = false
			        }
			      });
			    });
			  });
			},
			async loadImage() {
				this.isRenewal = false
				try {
					const cachedMedia = await mediaCache.loadMedia(this.src, this.uploadType, this.fileTpye);
					this.srcurl = cachedMedia;
				} catch (error) {
					console.log(error);
					this.errorHandler()
				}
			},
			// 图片加载时失败时触发
			errorHandler() {
				this.srcurl = this.defaultUrl
			},
			onAvatarClick(event) {
				if(this.preview){
					uni.previewImage({
						urls: [this.srcurl],
						current: this.srcurl,
						showmenu: true
					});
					return
				}
				this.$emit('click',event);
			}
		}
	};
</script>
<style lang="scss" scoped>
	.my-avatar {
		display: flex;
		align-items: center;
		justify-content: center;
		&__image {
			&--circle {
				border-radius: 100px;
			}
	
			&--square {
				border-radius: 4px;
			}
			
			&--straight {
				border-radius: 0px;
			}
		}
	}
</style>